package com.example.demo.service.impl;

import com.example.demo.entity.changeuser;
import com.example.demo.entity.data;
import com.example.demo.entity.user;
import com.example.demo.entity.user1;
import com.example.demo.mapper.userMapper;
import com.example.demo.service.UserService;
import com.example.demo.utils.TokenUtil;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {
    @Resource
    private userMapper userMapper;
    @Resource
    private TokenUtil tokenUtil;

    @Override
    public String delete(@RequestBody data data)//删除用户
    {
        if(userMapper.delete(data.getUsername(),data.getPassword())==1)
        {
            return "删除成功";
        }
        else
        {return "密码错误";}
    }

    @Override

    public user1 log(@RequestBody data data, HttpServletResponse response)//用户登录
    {
        System.out.println(data.getUsername());
        System.out.println(data.getPassword());
        user1 log= userMapper.log(data.getUsername(),data.getPassword());//检查账户密码

        if(log!=null)
        {
            String token = tokenUtil.generateToken(log);//签发token
            log.getToken(token);
            Cookie cookie = new Cookie("token", token);//设定cookie
            cookie.setPath("/");
            response.addCookie(cookie);
            return log;
        }
        else
            return null;
    }

    @Override
    public String register(@RequestBody user user)//注册用户
    {
        user user1=userMapper.SelectUsername(user.getUsername());//检查账号是否重复
        if(user1!=null)
        {return "用户名已存在";}
        else
        {
            int i = userMapper.register(user);
            if (i > 0)
                return "注册成功";
            else
                return "注册失败";
        }
    }

    @Override
    public List query()
    {
        return userMapper.query();
    }//查询用户信息

    @Override
    public String change(@RequestBody changeuser changeuser)//修改用户密码
    {
        if(userMapper.change(changeuser.getNewPassword(), changeuser.getUsername(), changeuser.getOldPassword())==1)
        {
            return "修改成功";
        }
        else
        {return "密码错误";}
    }

    @Override
    public String update(@RequestBody user user)//修改用户信息
    {
        if(userMapper.update(user)==0)
        {return "修改失败";}
        else
        {return "修改成功";}
    }
}
